<template>
  <div style="height:6vh;padding:10px 20px;background-color:#fff;display:flex;justify-content:space-between;align-items:center;">
    <span style="font-size:20px;font-weight:bold;">陪诊员管理</span>
    <el-button type="primary" @click="beforeAddEscort">新建陪诊员</el-button>
  </div>

  <!-- 新建陪诊员弹窗 -->
  <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="800px"
      :before-close="handleClose"
  >
    <el-form
        :model="addEscortForm"
        label-width="100px"
        label-position="left"
        style="padding:0 20px;"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="真实姓名" prop="realName">
            <el-input v-model="addEscortForm.realName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="addEscortForm.idCard"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="addEscortForm.gender">
              <el-radio label="male">男</el-radio>
              <el-radio label="female">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input v-model="addEscortForm.age" type="number"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="addEscortForm.phone"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务次数" prop="serviceCount">
            <el-input v-model="addEscortForm.serviceCount" type="number"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 头像上传 -->
      <el-form-item label="头像" style="text-align:left;">
        <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
          <img v-if="addEscortForm.avatar" :src="addEscortForm.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="个人简介" prop="profile">
        <el-input v-model="addEscortForm.profile" type="textarea" :rows="3"></el-input>
      </el-form-item>

      <el-form-item label="资质证书" prop="certificate">
        <el-upload
            class="certificate-uploader"
            :action="uploadUrl"
            :file-list="certificateFileList"
            :on-success="handleCertificateSuccess"
            :before-upload="beforeCertificateUpload"
            :on-remove="handleCertificateRemove"
            list-type="picture-card"
            :limit="3"
            multiple
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="审核状态" prop="status">
            <el-select v-model="addEscortForm.status" style="width:100%;">
              <el-option label="等待" value="pending"></el-option>
              <el-option label="通过" value="approved"></el-option>
              <el-option label="拒绝" value="rejected"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审核意见" prop="auditComment">
            <el-input v-model="addEscortForm.auditComment"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span style="flex:1"></span>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="addEscort">保存</el-button>
    </template>
  </el-dialog>

  <!-- 编辑陪诊员弹窗 -->
  <el-dialog
      :title="updateDialogTitle"
      v-model="updateDialogVisible"
      width="800px"
      :before-close="handleUpdateClose"
  >
    <el-form
        :model="EditEscortForm"
        label-width="100px"
        label-position="left"
        style="padding:0 20px;"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="真实姓名" prop="realName">
            <el-input v-model="EditEscortForm.realName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="EditEscortForm.idCard"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="EditEscortForm.gender">
              <el-radio label="male">男</el-radio>
              <el-radio label="female">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input v-model="EditEscortForm.age" type="number"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="EditEscortForm.phone"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务次数" prop="serviceCount">
            <el-input v-model="EditEscortForm.serviceCount" type="number"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 头像上传 -->
      <el-form-item label="头像" style="text-align:left;">
        <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleEditAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
          <img v-if="EditEscortForm.avatar" :src="EditEscortForm.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="个人简介" prop="profile">
        <el-input v-model="EditEscortForm.profile" type="textarea" :rows="3"></el-input>
      </el-form-item>

      <el-form-item label="资质证书" prop="certificate">
        <el-upload
            class="certificate-uploader"
            :action="uploadUrl"
            :file-list="certificateFileList"
            :on-success="handleCertificateSuccess"
            :before-upload="beforeCertificateUpload"
            :on-remove="handleCertificateRemove"
            list-type="picture-card"
            :limit="3"
            multiple
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="审核状态" prop="status">
            <el-select v-model="EditEscortForm.status" style="width:100%;">
              <el-option label="等待" value="pending"></el-option>
              <el-option label="通过" value="approved"></el-option>
              <el-option label="拒绝" value="rejected"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审核意见" prop="auditComment">
            <el-input v-model="EditEscortForm.auditComment"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span style="flex:1"></span>
      <el-button @click="handleUpdateClose">取消</el-button>
      <el-button type="primary" @click="updateEscort">保存</el-button>
    </template>
  </el-dialog>
  <!-- 陪诊员搜索卡片 -->
  <el-card style="margin:20px;border-radius:8px;">
    <el-form :inline="true" style="display:flex;align-items:center;gap:15px;">
      <el-form-item label="陪诊员搜索" style="margin-bottom:0;flex:1;">
        <el-input
            placeholder="输入真实姓名"
            v-model="searchEscortForm.realName"
            style="width:100%"
        ></el-input>
      </el-form-item>
      <el-form-item style="margin-bottom:0;">
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadEscort">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 陪诊员列表卡片 -->
  <el-card style="margin:20px;border-radius:8px;">
    <el-table
        :data="escortArr"
        stripe
        style="width:100%"
        header-row-class-name="table-header"
    >
      <el-table-column label="编号" type="index" width="80" align="center"></el-table-column>
      <el-table-column label="真实姓名" prop="realName" align="center"></el-table-column>
      <el-table-column label="手机号" prop="phone" align="center"></el-table-column>
      <el-table-column label="加入时间" prop="createTime" align="center"></el-table-column>
      <el-table-column label="审核状态" prop="status" align="center">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ formatStatus(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="评分" prop="avgRating" align="center">
        <template #default="scope">
          <el-rate v-model="scope.row.avgRating" disabled show-score />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template #default="scope">
          <el-button link type="primary" @click="editEscort(scope.row.id)">编辑</el-button>
          <el-button
              link
              type="danger"
              :disabled="scope.row.level==40"
              @click="deleteEscort(scope.row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 页脚 -->
  <footer class="app-footer">
    <div class="container">
      <div class="footer-content">
        <p class="footer-title">安心陪诊后台管理系统</p>
        <p class="footer-links">
          &copy; 2025 安心陪诊平台 版权所有 |
          <a href="#" @click.prevent="goToUserAgreement">用户协议</a> |
          <a href="#" @click.prevent="goToPrivacyPolicy">隐私政策</a>
        </p>
      </div>
    </div>
  </footer>
</template>

<script setup>
import { onMounted, ref } from "vue";
import axios from "axios";
import qs from "qs";
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from '@element-plus/icons-vue';

const BASE_URL = 'http://localhost:8080';
const router = useRouter();

// 弹窗控制
const dialogVisible = ref(false);
const updateDialogVisible = ref(false);
const dialogTitle = ref('新建陪诊员');
const updateDialogTitle = ref('编辑陪诊员');

// 表单数据
const addEscortForm = ref({
  id: '',
  realName: '',
  gender: '',
  age: '',
  idCard: '',
  phone: '',
  avatar: '',
  certificate: '',
  serviceCount: '',
  avgRating: '',
  profile: '',
  status: '',
  auditComment: '',
});

const EditEscortForm = ref({});
const searchEscortForm = ref({ realName: '' });
const escortArr = ref([]);

//  上传图片的url
const uploadUrl = `${BASE_URL}/v1/upload`;
const avatarFileList = ref([])
const certificateFileList = ref([]);

// 上传头像处理方法
const handleAvatarSuccess = (response) => {
  console.log(response)
  if (response.state === 2000) {
    addEscortForm.value.avatar = response.data;
    console.log(addEscortForm.value.avatar)
    ElMessage.success('头像上传成功');
  } else {
    ElMessage.error(response.message || '头像上传失败');
  }
};

const handleEditAvatarSuccess = (response) => {
  if (response.state === 2000) {
    EditEscortForm.value.avatar = response.data;
    console.log(EditEscortForm.value.avatar)
    ElMessage.success('头像上传成功');
  } else {
    ElMessage.error(response.message || '头像上传失败');
  }
};

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过2MB!')
  }
  return isImage && isLt2M
}

const handleAvatarRemove = () => {
  registerForm.value.avatar = ''
}

const handleAvatarExceed = () => {
  ElMessage.warning('只能上传一张头像图片')
}

// 上传资质证书成功处理
const handleCertificateSuccess = (response) => {
  console.log(response)
  if (response.state === 2000) {
    console.log(response.data)
    addEscortForm.value.certificate = response.data
    console.log(addEscortForm.value.certificate)
    ElMessage.success('资质证书上传成功');
  } else {
    ElMessage.error(response.message || '资质证书上传失败');
  }
};

const handleCertificateRemove = () => {
  addEscortForm.value.certificate = ''
};

const handleCertificateExceed = () => {
  ElMessage.warning('请将全部文件放入一份PDF')
}

const beforeCertificateUpload = (file) => {
  const isAllowedType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isAllowedType) {
    ElMessage.error('只能上传JPG/PNG/PDF文件!')
  }
  if (!isLt5M) {
    ElMessage.error('文件大小不能超过5MB!')
  }
  return isAllowedType && isLt5M
}

// 业务方法
const beforeAddEscort = () => {
  dialogTitle.value = '新增陪诊员';
  dialogVisible.value = true;
  addEscortForm.value = {
    id: '',
    realName: '',
    gender: '',
    age: '',
    idCard: '',
    phone: '',
    avatar: '',
    certificate: [],
    serviceCount: '',
    avgRating: '',
    profile: '',
    status: '',
    auditComment: '',
  };
};

const editEscort = (id) => {
  updateDialogTitle.value = '编辑陪诊员';
  updateDialogVisible.value = true;

  axios.get(`${BASE_URL}/v1/managerEscort/${id}`).then((response) => {
    if (response.data.state == 2000) {
      EditEscortForm.value = response.data.data;
      console.log(EditEscortForm.value)
    } else {
      ElMessage.error(response.data.msg + "出错了");
    }
  });
};

const addEscort = () => {
  axios.post(`${BASE_URL}/v1/managerEscort/add`, addEscortForm.value)
      .then(response => {
        if (response.data.state === 2000) {
          ElMessage.success('保存成功');
          dialogVisible.value = false;
          loadEscort();
        } else {
          ElMessage.error(response.data.message || '操作失败');
        }
      })
      .catch(error => {
        console.error("请求失败:", error);
        ElMessage.error(error.response?.data?.message || '请求失败，请检查数据格式');
      });
};

const updateEscort = () => {
  axios.post(`${BASE_URL}/v1/managerEscort/update`, EditEscortForm.value)
      .then(response => {
        if (response.data.state === 2000) {
          ElMessage.success('更新成功');
          EditEscortForm.value = {};
          updateDialogVisible.value = false;
          loadEscort();
        } else {
          ElMessage.error(response.data.message || '操作失败');
        }
      })
      .catch(error => {
        console.error("请求失败:", error);
        ElMessage.error(error.response?.data?.message || '请求失败，请检查数据格式');
      });
};
const deleteEscort = (id) => {
  ElMessageBox.confirm('您确认要删除该陪诊员吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.post(`${BASE_URL}/v1/managerEscort/delete/${id}`)
        .then((response) => {
          if (response.data.state === 2000) {
            ElMessage.success('删除成功!');
            loadEscort();
          } else {
            ElMessage.error(response.data.msg);
          }
        }).catch((error) => {
      console.error("删除请求失败:", error);
      ElMessage.error('删除请求失败，请检查网络连接');
    });
  }).catch(() => {
    ElMessage.info('已取消删除操作');
  });
};

const loadEscort = () => {
  let data = qs.stringify(searchEscortForm.value);
  axios.get(`${BASE_URL}/v1/managerEscort/select?${data}`)
      .then((response) => {
        if (response.data.state == 2000) {
          escortArr.value = response.data.data;
        } else {
          ElMessage.error(response.data.msg + "出错了");
        }
      });
};

const resetSearch = () => {
  searchEscortForm.value = {};
  loadEscort();
};

const handleClose = () => {
  if (confirm('确认取消保存陪诊员信息吗？')) {
    dialogVisible.value = false;
    addEscortForm.value = {};
  }
};

const handleUpdateClose = () => {
  if (confirm('确认取消更新陪诊员信息吗？')) {
    updateDialogVisible.value = false;
    EditEscortForm.value = {};
  }
};

onMounted(() => {
  loadEscort();
});
</script>

<style scoped>
  /* 表格标题样式 */
.table-header {
  background-color: #f5f7fa;
  font-weight: bold;
}

/* 卡片阴影效果 */
.el-card {
  box-shadow: 0 1px 4px rgba(0,0,0,0.1);
}

/* 头像上传样式 */
.avatar-uploader {
  display: inline-block;
  margin-left: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

/* 资质证书上传样式 */
.certificate-uploader :deep(.el-upload-list__item) {
  width: 120px;
  height: 120px;
  margin-right: 10px;
}

.certificate-uploader :deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
  line-height: 120px;
}

/* 弹窗底部按钮居中 */
.el-dialog__footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 20px 20px;
}

/* 状态标签样式 */
.status-pending {
  color: #e6a23c;
  background-color: #fdf6ec;
  border-color: #f5dab1;
}

.status-approved {
  color: #67c23a;
  background-color: #f0f9eb;
  border-color: #e1f3d8;
}

.status-rejected {
  color: #f56c6c;
  background-color: #fef0f0;
  border-color: #fde2e2;
}

  /* 页脚样式 */
  .app-footer {
    background-color: #f5f7fa;
    padding: 25px 0;
    border-top: 1px solid #e6e6e6;
    margin-top: 40px;
  }

  .footer-content {
    text-align: center;
  }

  .footer-title {
    color: #606266;
    margin-bottom: 12px;
    font-size: 15px;
  }

  .footer-links {
    color: #909399;
    font-size: 13px;
  }

  .footer-links a {
    color: #909399;
    transition: color 0.3s;
    margin: 0 5px;
  }

  .footer-links a:hover {
    color: #a6d2ff;
  }
</style>

<script>
// 添加状态格式化方法
const formatStatus = (status) => {
  const statusMap = {
    pending: '等待审核',
    approved: '已通过',
    rejected: '已拒绝'
  };
  return statusMap[status] || status;
};

const getStatusTagType = (status) => {
  const typeMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  };
  return typeMap[status] || '';
};
</script>